package com.itheima.reggie.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.config.BaseContext;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;


    /**
     * 用户下单添加订单和订单明细表
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        Long userId = BaseContext.getThreadLocal();
        long orderId = IdWorker.getId();

        if (userId == null){
            throw new CustomException("登录用户不存在");
        }

//        通过userId获取到user对象
        User user = userService.getById(userId);

        AtomicInteger atomic = new AtomicInteger(0);

//        订单明细表
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);

        if (shoppingCartList == null || shoppingCartList.size() <= 0){
            throw new CustomException("购物车为空");
        }

        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            if (shoppingCart.getDishId() != null){
                orderDetail.setDishId(shoppingCart.getDishId());
            }
            if (shoppingCart.getSetmealId() != null){
                orderDetail.setSetmealId(shoppingCart.getSetmealId());
            }
            if (shoppingCart.getDishFlavor() != null){
                orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            }
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());
            BigDecimal bigDecimal = new BigDecimal(orderDetail.getNumber()).multiply(orderDetail.getAmount());
            atomic.addAndGet(bigDecimal.intValue());
            orderDetailList.add(orderDetail);
        }

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null){
            throw new CustomException("还没有输入地址哦!");
        }
        String phone = addressBook.getPhone();
        String address = (addressBook.getProvinceName() != null ? addressBook.getProvinceName() :"")
                        +(addressBook.getCityName() != null ? addressBook.getCityName() : "")
                        +(addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "")
                        +(addressBook.getDetail()!= null ? addressBook.getDetail() : "");
        String consignee = addressBook.getConsignee();
//        订单orders的设置参数
        orders.setId(orderId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setStatus(2);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPhone(phone);
        orders.setAddress(address);
        orders.setConsignee(consignee);
        orders.setAmount(new BigDecimal(atomic.get()));

//        保存订单表
        save(orders);
//        保存订单明细表
        orderDetailService.saveBatch(orderDetailList);
//        清空购物车
        shoppingCartService.remove(lqw);
    }


}